/*
 * @Descripttion: 
 * @version: 
 * @Author: cc
 * @Date: 2023-05-02 18:46:46
 */
//引入连接数据库
const db = require('../config/db')

//分页获取一对一消息数据 data:uid fid curPage pageSize
exports.getmsg = (data, res) => {
    let offset = (data.curPage - 1) * data.pageSize;  //偏移量
    let sql = 'SELECT a.userid,b.imgurl,a.message,a.types,a.time ' +
        ' FROM (SELECT userid,message,types,time FROM message WHERE' +
        ' (userid = ? AND friendid = ?) OR (userid = ? AND friendid = ?)) as a, ' +
        '(SELECT userid,imgurl from `user`) as b WHERE b.userid = a.userid ORDER BY a.time DESC LIMIT ?,?';
    db.query(sql, [parseInt(data.uid), parseInt(data.id), parseInt(data.id), parseInt(data.uid), parseInt(offset), parseInt(data.pageSize)], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        else {
            res.sendMsg('success', 200, result)
        }
    })
}

//分页获取群聊消息 gid curPage pageSize
exports.getGroupMsg = (data, res) => {
    let offset = (data.curPage - 1) * data.pageSize
    let sql = 'SELECT a.groupid,a.userid,a.message,a.types,a.time,b.username,b.imgurl FROM `groupmsg` as a,' +
        ' (SELECT userid,username,imgurl FROM `user`) as b WHERE a.groupid = ? and b.userid=a.userid ORDER BY time DESC LIMIT ?,?'
    db.query(sql, [parseInt(data.gid), parseInt(offset), parseInt(data.pageSize)], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        else {
            res.sendMsg('success', 200, result)
        }
    })
}

//添加群消息
exports.addGroupMsg = (gid, uid, msg, types, res) => {
    let data = {
        groupid: gid,
        userid: uid,
        message: msg,
        types: types,
        time: new Date(),
        state: 1
    }
    let sql = 'insert into `groupmsg` set ?'
    db.query(sql, data, (err, result) => {
        if (res) {
            if (err) return res.sendMsg(err, 400)
            if (result.affectedRows != 1) return res.sendMsg('添加消息失败', 400)
            else {
                res.sendMsg('success', 200)
            }
        }
    })
}
